package com.zc.mall.controller;

import com.zc.mall.consts.MallConst;
import com.zc.mall.form.UserLoginForm;
import com.zc.mall.form.UserRegisterForm;
import com.zc.mall.pojo.User;
import com.zc.mall.service.IUserService;
import com.zc.mall.vo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * @author 曾川
 * @version 1.0.0
 * @ClassName UserController.java
 * @Description 用户Controller
 * @createTime 2021年06月02日 17:18:00
 */
@RestController
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;


    @PostMapping("/user/register")
    public ResponseVo<User> register(@Valid @RequestBody UserRegisterForm userForm) {
        //注册
        User user = new User();
        BeanUtils.copyProperties(userForm,user);
        return userService.register(user);
    }


    @PostMapping("/user/login")
    public ResponseVo<User> login(@Valid @RequestBody UserLoginForm userForm,
                                    HttpSession session) {
        //登录
        ResponseVo<User> userResponseVo = userService.login(userForm.getUsername(), userForm.getPassword());

        //设置session
        session.setAttribute(MallConst.CURRENT_USER,userResponseVo.getData());
        log.info("/login sessionId = {}  ",session.getId());
        return userResponseVo;
    }

    @GetMapping("/user")
    public ResponseVo<User> userInfo(HttpSession session) {
        log.info("/user sessionId = {}  ",session.getId());
        User user = (User) session.getAttribute(MallConst.CURRENT_USER);
        return ResponseVo.success(user);
    }

    @PostMapping("/user/logout")
    public ResponseVo<User> logout(HttpSession session) {
        log.info("/user/logout sessionId = {}",session.getId());
        session.removeAttribute(MallConst.CURRENT_USER);
        return ResponseVo.success();

    }


}
